﻿using FC.Utils;
using FC.Weather.Weatherdt.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FC.Weather.Weatherdt
{
    /// <summary>
    /// 中国天气网 气象数据集市
    /// </summary>
    public class WeatherdtWeather
    {
        /// <summary>
        /// 从 中国天气网 气象数据集市 获取天气情况
        /// </summary>
        /// <param name="area">地区,(101)全国</param>
        /// <param name="key">天气数据类型 forecast(预报)|observe(实况)|alarm(预警)|air(空气质量)|index(指数)</param>
        /// <param name="type">密钥</param>
        /// <returns></returns>
        public WeatherModel GetWeather(string area, string key, string type = "forecast")
        {
            string url = $"http://api.weatherdt.com/common/?area={area}&type={type}&key={key}";
            Uri httpURL = new Uri(url);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
            HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
            Stream respStream = httpResp.GetResponseStream();
            StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
            string jsonContent = respStreamReader.ReadToEnd();
            WeatherModel weather = jsonContent.FormatForecast().ToClass<WeatherModel>();
            return weather;
        }
    }
}
